package com.liyunc.demo.detect.camera;

import com.liyunc.demo.detect.utils.Constants;
import org.bytedeco.javacv.FFmpegFrameRecorder;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.FrameRecorder;

import static org.bytedeco.javacpp.avcodec.AV_CODEC_ID_MPEG4;
import static org.bytedeco.javacpp.avutil.AV_PIX_FMT_YUV420P;

/**
 * 录制摄像头视频，保存为MP4文件.
 */
public class RecordCameraSaveMp4 extends AbstractCameraApplication {

    // 音频通道，0表示无
    private static final int AUDIO_CHANNELS = 0;

    // 帧录制器
    protected FrameRecorder recorder;
    private final String savePath;

    public RecordCameraSaveMp4(String savePath) {
        this.savePath = savePath;
    }

    @Override
    protected void initOutput() throws Exception {
        // 实例化FFmpegFrameRecorder
        recorder = new FFmpegFrameRecorder(savePath,
                getCameraImageWidth(),
                getCameraImageHeight(),
                AUDIO_CHANNELS);
        // 文件格式
        recorder.setFormat(Constants.VIDEO_TYPE);
        // 帧率与抓取器一致
        recorder.setFrameRate(getFrameRate());
        // 编码格式
        recorder.setPixelFormat(AV_PIX_FMT_YUV420P);
        // 编码器类型
        recorder.setVideoCodec(AV_CODEC_ID_MPEG4);
        // 视频质量，0表示无损
        recorder.setVideoQuality(0);
        // 初始化
        recorder.start();
    }

    @Override
    protected void output(Frame frame) throws Exception {
        // 存储到磁盘
        recorder.record(frame);
    }

    @Override
    protected void releaseOutputResource() throws Exception {
        recorder.close();
    }
}
